//
//  KPChooseImageView.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/3/22.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import UIKit
import TangramKit
import RxSwift
import TZImagePickerController

class KPChooseImageView: TGFlowLayout, TZImagePickerControllerDelegate {

    let bag = DisposeBag()

    fileprivate var maxChooseCount: Int = 0
    fileprivate var chooseImageButton: KPButton!
    fileprivate var chooseButtonView: UIView!
    fileprivate var imagePicker: TZImagePickerController!

    var imageArray : [UIImage] = [UIImage]()
    var images = Variable([UIImage]())
    var imageUrls = Variable([String]())

    override init(frame: CGRect, orientation: TGOrientation, arrangedCount: Int) {
        super.init(frame: frame, orientation: orientation, arrangedCount: arrangedCount)
    }

    convenience init(orientation: TGOrientation, arrangedCount: Int, maxChooseCount: Int) {
        self.init(frame: .zero, orientation: orientation, arrangedCount: arrangedCount)
        self.maxChooseCount = maxChooseCount
        tg_padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        tg_space = 10
        tg_height.equal(.wrap)
        tg_gravity = TGGravity.horz.fill
        prepareView()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func getImages() -> [UIImage] {
        return self.subviews.filter { $0 is KPChooseImageItem }.compactMap({ (view) -> UIImage? in
            if let view = view as? KPChooseImageItem {
                return view.imageView.image!
            }
            return nil
        })
    }

    fileprivate func prepareChooseImageView() {

        chooseImageButton = KPButton.init(image: #imageLiteral(resourceName: "相机"), title: "点击上传图片")
        chooseImageButton.imagePosistion = .top
        chooseImageButton.titleImageSpacing = 8
        chooseImageButton.backgroundColor = .white
        chooseImageButton.titleLabel?.font = 13.font
        chooseImageButton.setTitleColor(#colorLiteral(red: 0.3725490196, green: 0.3725490196, blue: 0.3725490196, alpha: 1), for: .normal)
        chooseImageButton.tg_height.equal(chooseImageButton.tg_width)
        chooseImageButton.cornerRadius = 4

        chooseImageButton.addTarget(self, action: #selector(chooseImage(sender:)), for: .touchUpInside)

    }

    @objc
    func chooseImage(sender: KPButton) {
        KPLog("123")
        imagePicker = nil
        imagePicker = TZImagePickerController.init(maxImagesCount: maxChooseCount - getImages().count, columnNumber: 4, delegate: self, pushPhotoPickerVc: true)
        imagePicker.allowTakePicture = true
        imagePicker.allowPickingImage = true
        imagePicker.didFinishPickingPhotosHandle = { photos, assets, isOriginal in
            if let photos = photos {
                self.images.value = photos
            }
        }

        applicationKeyWindow!.rootViewController?.present(imagePicker, animated: true, completion: nil)
    }

    // MARK: - 创建视图
    fileprivate func prepareView() {
        prepareChooseImageView()

        images.asObservable()
            .skip(1)
            .subscribe(onNext: { [unowned self] (images) in
                self.chooseImageButton.removeFromSuperview()
                guard !images.isEmpty else {
                    self.addSubview(self.chooseImageButton)
                    return
                }

                for image in images {
                    let imageItem = KPChooseImageItem.init()
                    imageItem.imageView.image = image
                    imageItem.deleteButton.addTarget(for: .touchUpInside, action: { [unowned self] (sender) in
                        sender.superview?.removeFromSuperview()
                        if self.subviews.count < self.maxChooseCount {
                            self.addSubview(self.chooseImageButton)
                        }
                        self.tg_layoutAnimationWithDuration(0.25)

                    })
                    imageItem.tg_height.equal(imageItem.tg_width)
                    self.addSubview(imageItem)
                }
                if self.subviews.count < self.maxChooseCount {
                    self.addSubview(self.chooseImageButton)
                }

            }).disposed(by: bag)

        imageUrls.asObservable()
            .subscribe(onNext: { (urls) in
                self.chooseImageButton.removeFromSuperview()
                guard !urls.isEmpty else {
                    self.addSubview(self.chooseImageButton)
                    return
                }

                for url in urls {
                    let imageItem = KPChooseImageItem.init()
                    imageItem.imageView.kf.setImage(url)
                    imageItem.deleteButton.addTarget(for: .touchUpInside, action: { [unowned self] (sender) in
                        sender.superview?.removeFromSuperview()
                        if self.subviews.count < self.maxChooseCount {
                            self.addSubview(self.chooseImageButton)
                        }
                        self.tg_layoutAnimationWithDuration(0.25)
                    })
                    imageItem.tg_height.equal(imageItem.tg_width)
                    self.addSubview(imageItem)
                }
                if self.subviews.count < self.maxChooseCount {
                    self.addSubview(self.chooseImageButton)
                }

            }).disposed(by: bag)
    }
}

class KPChooseImageItem: TGRelativeLayout {
    var deleteButton: UIButton!
    var imageView: UIImageView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareView()
    }
    convenience init() {
        self.init(frame: .zero)
        prepareView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 创建视图
    fileprivate func prepareView() {
        contentMode = .scaleAspectFill
        cornerRadius = 4

        imageView = UIImageView.init().then {
            addSubview($0)
            $0.contentModeScaleToFill()
            $0.tg_top.equal(7.5)
            $0.tg_right.equal(7.5)
            $0.tg_size(width: .fill, height: .fill)
        }
        deleteButton = UIButton.init(image: #imageLiteral(resourceName: "图片删除"), title: nil).then {
            addSubview($0)
            $0.tg_top.equal(0)
            $0.tg_right.equal(0)
            $0.tg_size(width: 15, height: 15)
        }
    }
}
